﻿using Devonline.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace Devonline.Communication.Server;

/// <summary>
/// 消息可持久化保存的服务器
/// </summary>
public class PersistentMessageServer : MessageServer
{
    protected readonly ApplicationDbContext _messageContext;
    public PersistentMessageServer(
        ILogger<PersistentMessageServer> logger,
        IDistributedCache cache,
        IHttpContextAccessor httpContextAccessor,
        HostSetting hostSetting,
        ApplicationDbContext messageContext
        ) : base(logger, cache, httpContextAccessor, hostSetting)
    {
        _messageContext = messageContext;
    }

    /// <summary>
    /// 消息持久化保存方式
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    protected override async Task SaveMessageAsync(Message message)
    {
        await base.SaveMessageAsync(message);
        if (_messageContext.Messages is not null && message.ReceiveTime is not null)
        {
            _logger.LogDebug($"Server will save the {message.Type} message to database which from sender {message.Sender} in client {Client} to receiver {message.Receiver} with message id: {message.Id}");
            var originalMessage = await _messageContext.Messages.AsNoTracking().FirstOrDefaultAsync(x => x.Id == message.Id);
            if (originalMessage is null)
            {
                _messageContext.Messages.Add(message);
            }
            else
            {
                _messageContext.Messages.Update(message.CopyTo(originalMessage));
            }

            await _messageContext.SaveChangesAsync();
            _logger.LogInformation($"Server has been saved the {message.Type} message to database which from sender {message.Sender} in client {Client} to receiver {message.Receiver} with message id: {message.Id}");
        }
    }
}